package com.btex.app;

import android.content.ClipData;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.taobao.windvane.webview.WVWebChromeClient;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.btex.app.tools.SharedPreferencesUtil;
import com.btex.app.tools.ToUI;
import com.btex.app.tools.Tools;
import com.handmark.pulltorefresh.library.PullToRefreshWebView;

import java.io.File;
import java.util.HashMap;
import java.util.Map;


public class WebActivity extends BaseActivity {
    private static final java.lang.String TAG = "WebActivity";
    private WebView webView = null;
    private String web_url = null;
    private WebSettings webSettings = null;
    PullToRefreshWebView mPullRefreshWebView;
    private ProgressBar pb = null;
    private SharedPreferencesUtil sp;
    //新增加webview图片上传
    private ValueCallback<Uri> mSingleFileCallback;
    private ValueCallback<Uri[]> mMultiFileCallback;
    private Uri imageUri;
    ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);

        mPullRefreshWebView = (PullToRefreshWebView) findViewById(R.id.pull_refresh_webview);
        pb = (ProgressBar) findViewById(R.id.pb);

        pb.setIndeterminate(true);
        pb.bringToFront();

        webView = mPullRefreshWebView.getRefreshableView();
        webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);
        sp = SharedPreferencesUtil.getSharedPreferences(this);
        boolean isEngilsh = sp.getBoolean("isEngilsh", false);
        token = sp.getString(Config.TOKEN, null);
        Intent intent_data = getIntent();
        web_url = intent_data.getStringExtra("web_url");

        if (isEngilsh) {

            if (web_url.contains("?")) {
                web_url = web_url + "&lang=en";
            } else {
                web_url = web_url + "?lang=en";
            }

        } else {
            if (web_url.contains("?")) {
                web_url = web_url + "&lang=zh_cn";
            } else {
                web_url = web_url + "?lang=zh_cn";
            }
        }

        initData();

    }


    @Override
    public void setData() {

        String isEnglish;
        boolean isEngilsh = sp.getBoolean("isEngilsh", false);
        if (isEngilsh) {
            isEnglish = "en";
        } else {
            isEnglish = "zh_cn";
        }


        webView.setWebChromeClient(new WVWebChromeClient() {

            @Override
            public void onReceivedTitle(WebView view, String title) {
                tv_title.setText(title);
            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                Log.e("Webview", "onShowFileChooser");
                mMultiFileCallback = filePathCallback;
                openGallery();

                return true;  // 一定要return true 防止下次回到 WebView页面重新调用，抛异常 duplicate result
            }

            // 5.0以下的文件上传监听方法
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                Log.e("Webview", "openFileChooser");
                mSingleFileCallback = uploadMsg;
                openGallery();
            }

        });

        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                pb.setIndeterminate(true);
                pb.bringToFront();

                Intent i = new ToUI().toUi(cxt, url);
                if (i != null) {
                    startActivity(i);
                    return true;
                }

                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                pb.setVisibility(View.GONE);
                String title = view.getTitle();
                if (!TextUtils.isEmpty(title) && !title.contains("www") && !cxt.getString(R.string.no_found_web_page).equals(title))
                    if (title.contains("?")) {
                        String[] split = title.split("[?]");
                        String s = split[0];
                        tv_title.setText(s);

                    } else {
                        tv_title.setText(title);
                    }

                view.loadUrl("javascript:window.local_obj.showSource(document.title);");
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                pb.setVisibility(View.GONE);
                view.loadUrl("file:///android_asset/no_network.html");
                super.onReceivedError(view, errorCode, description, failingUrl);
            }
        });

        if (web_url.contains("https://btex.me/") || web_url.contains("http://android.kongniu.cn/")) {

            if (web_url.contains("return_fees_by_day")) {

                Map<String, String> extraHeaders = new HashMap<String, String>();
                extraHeaders.put("Cookie", "");
                extraHeaders.put("Token", "");
                extraHeaders.put("SESSID", "");
                extraHeaders.put("myversion", Tools.getVersion(this));
                extraHeaders.put("myclient", "android");
                extraHeaders.put("lang", isEnglish);

                if (web_url.indexOf("window=new") != -1) {
                    web_url = web_url.replaceAll("window=new", "");
                }

                webView.loadUrl(web_url, extraHeaders);

                return;

            }

            if (web_url.contains("news/index/help")) {

                Map<String, String> extraHeaders = new HashMap<String, String>();
                extraHeaders.put("Cookie", "");
                extraHeaders.put("Token", "");
                extraHeaders.put("SESSID", "");
                extraHeaders.put("myversion", Tools.getVersion(this));
                extraHeaders.put("myclient", "android");
                extraHeaders.put("lang", isEnglish);

                if (web_url.indexOf("window=new") != -1) {
                    web_url = web_url.replaceAll("window=new", "");
                }

                webView.loadUrl(web_url, extraHeaders);

                return;

            }

            if (web_url.contains("news/index/help")) {

                Map<String, String> extraHeaders = new HashMap<String, String>();
                extraHeaders.put("Cookie", "");
                extraHeaders.put("Token", "");
                extraHeaders.put("SESSID", "");
                extraHeaders.put("myversion", Tools.getVersion(this));
                extraHeaders.put("myclient", "android");
                extraHeaders.put("lang", isEnglish);

                if (web_url.indexOf("window=new") != -1) {
                    web_url = web_url.replaceAll("window=new", "");
                }

                webView.loadUrl(web_url, extraHeaders);

                return;

            }

            if (web_url.contains("pub/helpdesk")) {

                Map<String, String> extraHeaders = new HashMap<String, String>();
                extraHeaders.put("Cookie", "");
                extraHeaders.put("Token", "");
                extraHeaders.put("SESSID", "");
                extraHeaders.put("myversion", Tools.getVersion(this));
                extraHeaders.put("myclient", "android");
                extraHeaders.put("lang", isEnglish);

                if (web_url.indexOf("window=new") != -1) {
                    web_url = web_url.replaceAll("window=new", "");
                }

                webView.loadUrl(web_url, extraHeaders);

                return;

            }

//            bt_introduce_m

            if (web_url.contains("bt_introduce_m")) {

                Map<String, String> extraHeaders = new HashMap<String, String>();
                extraHeaders.put("Cookie", "");
                extraHeaders.put("Token", "");
                extraHeaders.put("SESSID", "");
                extraHeaders.put("myversion", Tools.getVersion(this));
                extraHeaders.put("myclient", "android");
                extraHeaders.put("lang", isEnglish);

                if (web_url.indexOf("window=new") != -1) {
                    web_url = web_url.replaceAll("window=new", "");
                }

                webView.loadUrl(web_url, extraHeaders);

                return;

            }


            if (web_url.contains("news/index/ann")) {

                Map<String, String> extraHeaders = new HashMap<String, String>();
                extraHeaders.put("Cookie", "");
                extraHeaders.put("Token", "");
                extraHeaders.put("SESSID", "");
                extraHeaders.put("myversion", Tools.getVersion(this));
                extraHeaders.put("myclient", "android");
                extraHeaders.put("lang", isEnglish);

                if (web_url.indexOf("window=new") != -1) {
                    web_url = web_url.replaceAll("window=new", "");
                }

                webView.loadUrl(web_url, extraHeaders);

                return;

            }

            Map<String, String> extraHeaders = new HashMap<String, String>();
            extraHeaders.put("Cookie", token);
            extraHeaders.put("Token", token);
            extraHeaders.put("SESSID", token);
            extraHeaders.put("myversion", Tools.getVersion(this));
            extraHeaders.put("myclient", "android");
            extraHeaders.put("lang", isEnglish);

            if (web_url.indexOf("window=new") != -1) {
                web_url = web_url.replaceAll("window=new", "");
            }

            Log.i("keuhfwuehfwefuw", web_url);
            webView.loadUrl(web_url, extraHeaders);

        } else {

            Map<String, String> extraHeaders = new HashMap<String, String>();
            extraHeaders.put("Cookie", "");
            extraHeaders.put("Token", "");
            extraHeaders.put("SESSID", "");
            extraHeaders.put("myversion", Tools.getVersion(this));
            extraHeaders.put("myclient", "android");
            extraHeaders.put("lang", isEnglish);

            if (web_url.indexOf("window=new") != -1) {
                web_url = web_url.replaceAll("window=new", "");
            }

            webView.loadUrl(web_url, extraHeaders);

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                goBack();
                break;
        }
    }

    private void goBack() {
        if (webView.canGoBack()) {
            webView.goBack();//返回上一页面
        } else {
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            finish();
        }
    }

    private void openGallery() {
//        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
//        intent.setType("image/*");
//        startActivityForResult(intent, 100);

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, 100);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (mSingleFileCallback == null && mMultiFileCallback == null) {
                return;
            }
            Uri tempUri = null;
            if (data != null) {
                String url = getPath(WebActivity.this, data.getData());
                File temp = new File(url);
                tempUri = Uri.fromFile(temp);
            }

            if (mSingleFileCallback != null) { // 5.0以下处理方式
                if (data != null) {
                    mSingleFileCallback.onReceiveValue(tempUri);
                } else {
                    mSingleFileCallback.onReceiveValue(imageUri);
                }
                mSingleFileCallback = null;
            } else if (mMultiFileCallback != null) { // 5.0版本以上
                Uri[] uris = null;
                if (data == null) {
                    uris = new Uri[]{imageUri};
                } else {
                    // 多选图片[图片一定要压缩，转化为base网页加载很慢]
                    String dataString = data.getDataString();
                    ClipData clipData = data.getClipData();
                    if (clipData != null) {
                        int size = clipData.getItemCount();
                        uris = new Uri[size];
                        for (int i = 0; i < size; i++) {
                            // 将所选图片的 url保存到 uris数组中
                            uris[i] = clipData.getItemAt(i).getUri();
                        }
                    }
                    if (!TextUtils.isEmpty(dataString)) {
                        uris = new Uri[]{Uri.parse(dataString)};
                    }
                }

                if (uris == null) {
                    mMultiFileCallback.onReceiveValue(null);
                    mMultiFileCallback = null;
                } else {
                    mMultiFileCallback.onReceiveValue(uris);
                    mMultiFileCallback = null;
                }
            }
        }

    }

    public static String getPath(Context mainActivity, Uri data) {
        String[] proj = {MediaStore.Images.Media.DATA};
        CursorLoader loader = new CursorLoader(mainActivity, data, proj, null, null, null);
        Cursor cursor = loader.loadInBackground();
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
}
